package com.xingyun.kingdee.erp.tools.response.util;

import com.alibaba.fastjson.JSONObject;
import com.xingyun.kingdee.erp.common.model.response.Result;
import com.xingyun.kingdee.erp.tools.common.exceptions.ErpResponseNotMeetExpectation;
import com.xingyun.kingdee.erp.tools.common.exceptions.ErpResponseRemoteException;
import com.xingyun.kingdee.erp.tools.response.model.save.ErpSaveFormResponse;

import java.util.Objects;

/**
 * @author lingo
 * @version v1.0
 * @date 2020/8/13 16:55
 * @Company www.xyb2b.com
 */

public class ErpReponseHelper {

    private static void checkRemoteSuccess(Result<?> result){
        if (!isRemoteResultSuccess(result)){
            throw new ErpResponseRemoteException();
        }
    }

    /**
     * 获取 Result.Result 里面的有用内容
     * @param data 数据内容
     * @return
     * @throws ErpResponseNotMeetExpectation
     */
    private static JSONObject getDoubleResultContent(JSONObject data) throws ErpResponseNotMeetExpectation {
        String outerDataFlag = "Result";
        String innerDataFlag = "ResponseStatus";
        if (data.containsKey(outerDataFlag) && data.getJSONObject(outerDataFlag).containsKey(innerDataFlag)){
            return data.getJSONObject(outerDataFlag).getJSONObject(innerDataFlag);
        }
        throw new ErpResponseNotMeetExpectation(data.toJSONString());
    }

    public static boolean isRemoteResultSuccess(Result<?> result) {
        return !Objects.isNull(result) && result.isSuccess();
    }

    public static ErpSaveFormResponse getSaveResponseFromResult(Result<JSONObject> saveFromResult){
        checkRemoteSuccess(saveFromResult);
        JSONObject doubleResultContent = getDoubleResultContent(saveFromResult.getData());
        return JSONObject.toJavaObject(doubleResultContent,ErpSaveFormResponse.class);
    }
}
